package com.dm0858.bianmin.mine.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSON;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.app.MyApp;
import com.dm0858.bianmin.databinding.ActivityLoginLayoutBinding;
import com.dm0858.bianmin.mine.base.BaseActivity;
import com.dm0858.bianmin.mine.bean.PhoneLoginBeanData;
import com.dm0858.bianmin.mine.listener.IResultListener;
import com.dm0858.bianmin.mine.network.RetrofitListener;
import com.dm0858.bianmin.mine.tools.SPUtils;
import com.dm0858.bianmin.mine.tools.ShapeUtils;
import com.dm0858.bianmin.mine.tools.ToastUtils;
import com.dm0858.bianmin.mine.viewmodel.LoginViewModel;
import com.dm0858.bianmin.wxapi.Constants;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;
import org.litepal.util.LogUtil;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements Spinner.OnItemSelectedListener,View.OnClickListener {

    public static final String action = "wxentry.broadcast.action";

    private ActivityLoginLayoutBinding binding;

    private LoginViewModel viewModel;

    //spinner的适配器
    private ArrayAdapter arrayAdapter;
    //区号
    private String[] areaCodes = new String[]{
            "+86", "+87", "+88", "+89", "+90"
    };
    private String areaCode = areaCodes[0];

    private IWXAPI api;

    //头像url
    private String avatar = "";
    //昵称
    private String nickName = "";
    //openid
    private String openid = "";
    //unionid
    private String unionid = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login_layout);
        binding.spinner.setOnItemSelectedListener(this);
        binding.setOnClick(this);
        //设置按钮的样式
        binding.btnGetCode.setBackground(
                new ShapeUtils()
                        .corner(2)
                        .lineColor(getResources().getColor(R.color.appTheme,null))
                        .lineWidth(1)
                        .build()
        );
        binding.btnLogin.setBackground(
                new ShapeUtils()
                        .corner(2)
                        .fill(getColor(R.color.appTheme))
                        .build()
        );
        initData();
    }

    @Override
    protected void initData() {
        //注册微信登录广播监听器
        registerReceiver();
        //手机号码区号
        arrayAdapter = new ArrayAdapter(this, R.layout.spinner_area_code_item_layout, R.id.txt_areaCode, areaCodes);
        binding.spinner.setAdapter(arrayAdapter);
        //微信api注册
        api= WXAPIFactory.createWXAPI(this, Constants.APP_ID,true);
        api.registerApp(Constants.APP_ID);
        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        getTime();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                onBackPressed();
                break;
            case R.id.btn_getCode:
                if (binding.edtPhone.getText().toString().equals("")) {
                    ToastUtils.showShort("手机号不能为空");
                    return;
                }
                viewModel.getCode(binding.edtPhone.getText().toString(), new IResultListener() {
                    @Override
                    public void onSuccess(Object object) {
                        setTime(60);
                    }
                });
                break;
            case R.id.btn_login:
                if (binding.edtPhone.getText().toString().equals("")) {
                    ToastUtils.showShort("手机号不能为空");
                    return;
                }
                if (binding.edtCode.getText().toString().equals("")) {
                    ToastUtils.showShort("请获取验证码");
                    return;
                }
                viewModel.login(binding.edtPhone.getText().toString(), binding.edtCode.getText().toString(), new RetrofitListener() {
                    @Override
                    public void onSuccess(Object object) {

                        PhoneLoginBeanData data = JSON.parseObject(object.toString(),PhoneLoginBeanData.class);
                        if (data != null) {
                            MyApp.userid = data.getId();
                            MyApp.phone = data.getPhone();
                            //手机号登录
                            MyApp.launchMode = 1;
                            SPUtils.getInstance("user_info").put("userid",MyApp.userid,true);
                            SPUtils.getInstance("user_info").put("phone",MyApp.phone,true);
                            SPUtils.getInstance("user_info").put("launchMode",MyApp.launchMode,true);
                            setResult(10002);
                            onBackPressed();
                        }
                    }

                    @Override
                    public void onError(int messageCode, String e) {
                        ToastUtils.showShort(e);
                    }
                });
                break;
            case R.id.img_weChat:
            case R.id.txt_weChat:
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "bmfuwu_wx_login";
                api.sendReq(req);
                break;
        }
    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        areaCode = areaCodes[i];
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterReceiver();
    }


    /////////////////////////////////////
    //广播接收器
    /////////////////////////////////////
    private IntentFilter intentFilter;
    private LoginReceiver receiver;

    class LoginReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            LoginActivity.this.setResult(10001,intent);
            LoginActivity.this.finish();
        }
    }

    /**
     * @description 注册监听器
     * @param
     * @return
     * @author 迪迪丶Sir
     * @since 2020-03-26
     **/
    private void registerReceiver() {
        intentFilter = new IntentFilter();
        intentFilter.addAction(action);
        receiver = new LoginReceiver();
        registerReceiver(receiver,intentFilter);
    }

    private void unRegisterReceiver() {
        if (receiver != null) unregisterReceiver(receiver);
    }

    /**
     * @description 设置时间开始倒计时
     * @param
     * @return
     * @author 迪迪丶Sir
     * @since 2020-04-09
     **/
    private CountDownTimer timer;
    private void setTime(int time) {
        //将倒计时结束时的时间保存
        SPUtils.getInstance("user_info").put("code_remainingTime",System.currentTimeMillis() + time * 1000,true);
        if (time > 0) {
            binding.btnGetCode.setTextColor(getResources().getColor(R.color.grey_700,null));
            if(binding.btnGetCode.isClickable())binding.btnGetCode.setClickable(false);
//            if (binding.txtCountdown.getVisibility() == View.INVISIBLE) binding.txtCountdown.setVisibility(View.VISIBLE);
            timer = new CountDownTimer(time * 1000,1000) {
                @Override
                public void onTick(long l) {
                    int seconds = (int)(l / 1000);
                    binding.btnGetCode.setText(seconds + "s");
                }

                @Override
                public void onFinish() {
                    binding.btnGetCode.setTextColor(getResources().getColor(R.color.appTheme,null));
                    binding.btnGetCode.setText("验证码");
                    if(!binding.btnGetCode.isClickable())binding.btnGetCode.setClickable(true);
                }
            };
            timer.start();
        }
        else {
            binding.btnGetCode.setTextColor(getResources().getColor(R.color.appTheme,null));
            if(!binding.btnGetCode.isClickable())binding.btnGetCode.setClickable(true);
        }
    }

    /**
     * @description 获取剩余倒计时
     * @param
     * @return
     * @author 迪迪丶Sir
     * @since 2020-04-09
     **/
    private void getTime() {
        //当前时间
        long currentTime = System.currentTimeMillis();
        //倒计时结束时的时间
        long countdown = SPUtils.getInstance("user_info").getLong("code_remainingTime",currentTime);
        //剩余时间
        int remainingTime = ((int)(currentTime - countdown)) / 1000;
        //如果剩余时间时负数，说明倒计时还没完
        if (remainingTime < 0) remainingTime = Math.abs(remainingTime);
        else remainingTime = 0;
        setTime(remainingTime);
    }

}